﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using eStore.Models;

namespace eStore
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        private IUserRepository userRepository = null;
        public MvcApplication():base(){
            userRepository = new UserRepository();
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute("DefaultPage",
                            "Default.aspx",
                            new { controller = "Home", action = "Index" }) ;

            routes.MapRoute("Browse",
                    "Store/Browse/{categoryname}",
                    new { controller = "Store", action = "Browse", categoryname = "" });

            routes.MapRoute("Details",
                        "Store/Details/{id}/{NewReview}",
                        new { controller = "Store", action = "Details", id = (string)null, NewReview=UrlParameter.Optional },
                        new {id=@"\d+"});


            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );



        }

        protected void Application_OnAuthenticateRequest(Object sender, EventArgs e)
        {
            if (Context.User != null)
            {
                if (Context.User.Identity.IsAuthenticated)
                {
                    User user = userRepository.GetUserByName(Context.User.Identity.Name);

                    if (user == null)
                    {
                        throw new ApplicationException("Context.User.Identity.Name is not a recognised user.");
                    }

                    System.Threading.Thread.CurrentPrincipal = Context.User = new eStoreUser(user.UserName, user.IsAdmin.Value == true ? "admin" : "user");
                    return;
                }
            }
            System.Threading.Thread.CurrentPrincipal = Context.User = eStoreUser.Guest;
        }


        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            RegisterRoutes(RouteTable.Routes);
        }
    }
}